/**
 iTextUploader
 (C) 2008 MyselftDev (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: UploadView.m 63 2009-02-07 16:28:48Z myselftdev $ */

#import "UploadView.h"

@implementation UploadView

#pragma mark Alloc/Dealloc
- (id)initWithFrame:(CGRect)frame
		 dataObject:(PreferencesData*)theDataObject
	 mainViewObject:(MainView*)theMainViewObject
{
	if ((self = [super initWithFrame:frame]))
	{
		data = [theDataObject retain];
		mainView = [theMainViewObject retain];
		
		self.backgroundColor = [UIColor colorWithWhite:1.0 alpha:1.0];
		
		UIButton *uploadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
		uploadButton.contentMode = UIViewContentModeRedraw;
		uploadButton.frame = CGRectMake(90.0, 40.0, 140.0, 40.0);
		uploadButton.font = [UIFont boldSystemFontOfSize:22.0];
		[uploadButton setTitle:@"Upload" forState:UIControlStateNormal];
		[uploadButton addTarget:self action:@selector(uploadButtonClicked) forControlEvents:UIControlEventTouchUpInside];
		[self addSubview:uploadButton];
		
		webFrame = [ [UIWebView alloc] initWithFrame:CGRectMake(frame.origin.x, 120.0, frame.size.width, (frame.size.height - 120.0))];
		webFrame.userInteractionEnabled = NO;
		webFrame.delegate = self;
		[self addSubview:webFrame];
		
		workingView = [[AlertBox alloc] initAlertBox];
		workingView.hidden = YES;
		
		NSURLRequest *aRequest=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"UploadViewMainText" ofType:@"html"]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
		[webFrame loadRequest:aRequest];
		
		import = [[ITUImport alloc] init];
	}
	return self;
}

- (void)dealloc {
	[import release];
	
	[webFrame release];
	[workingView release];
	
	[data release];
	[mainView release];
	
	[super dealloc];
}

#pragma mark Upload
- (void) uploadButtonClicked
{
	//[self performSelector:@selector(uploadMessages) withObject:nil afterDelay:0.5];
	
	import.delegate = self;
	import.username = [data getData:@"username"];
	import.password = [data getData:@"password"];
	import.lastId = [[data getData:@"lastid"] unsignedIntValue];
	
	UIProgressView *progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
	progressBar.frame = CGRectMake(40.0, 18.0, 170.0, 9.0);
	[workingView.alertView addSubview:progressBar];
	[progressBar autorelease];
	progressBar.hidden = YES;
	import.uploadProgressDelegate = progressBar;
	
	[NSThread detachNewThreadSelector:@selector(startRequest) toTarget:import withObject:nil];
	//[import startRequest];
}

- (void)setStatus:(NSNumber*)status
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSLog(@"Set status: %d", [status intValue]);
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	UIProgressView *progressBar = import.uploadProgressDelegate;
	workingView.activityIndicator.hidden = NO;
	progressBar.hidden = YES;
	
	workingView.hidden = NO;
	
	switch ([status intValue]) {
		case kImportComplete:
			workingView.hidden = YES;
			NSLog(@"Completed. Message: %@", import.returnData);
			//[self performSelectorOnMainThread:@selector(uploadDoneWithMessage:) withObject:import.returnData waitUntilDone:YES];
			[self uploadDoneWithMessage:import.returnData];
			break;
		
		case kImportError:
			workingView.hidden = YES;
			NSLog(@"Error. Message: %@", import.returnData);
			//[self performSelectorOnMainThread:@selector(uploadDoneWithMessage:) withObject:import.returnData waitUntilDone:YES];
			[self uploadDoneWithMessage:import.returnData];
			break;
		
		case kImportStatusAddressBookNoNewElements:
			workingView.hidden = YES;
			NSLog(@"There aren't new elements to import");
			//[self performSelectorOnMainThread:@selector(uploadDoneWithMessage:) withObject:import.returnData waitUntilDone:YES];
			[self uploadDoneWithMessage:
			 [NSDictionary dictionaryWithObjectsAndKeys:
			  [NSNumber numberWithBool:NO], @"error",
			  @"There aren't new elements in your Address Book", @"message",
			  nil
			 ]];
			break;
			
		case kImportStatusStarting:
			workingView.text = @"Starting...";
			break;
		
		case kImportStatusLoadingAddressBook:
			[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
			workingView.text = @"Loading Address Book...";
			break;
		
		case kImportStatusReceivedAddressBook:
			workingView.text = @"Parsing Address Book...";
			break;
		
		case kImportStatusPreparingData:
			workingView.text = @"Preparing Data...";
			break;
			
		case kImportStatusUploading:
			workingView.text = @"Uploading...";
			[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
			workingView.activityIndicator.hidden = YES;
			progressBar.hidden = NO;
			break;
			
		default:
			workingView.text = @"Working...";
			break;
	}
	
	[pool release];
}

- (void)uploadDoneWithMessage: (NSDictionary*)message
{
	[message retain];
	
	BOOL error = [[message objectForKey:@"error"] boolValue];
	NSString *resultString = [message objectForKey:@"message"];
	
	if(!error)
	{
		NSUInteger currentTimestamp = (NSUInteger) [ [NSDate date] timeIntervalSince1970];
		[data setValue:[NSNumber numberWithUnsignedInteger:currentTimestamp] forData:@"lastupload"];
		if(import.lastId > 0)
		{
			NSLog(@"Updated lastid - old: %u, new: %u", [[data getData:@"lastid"] unsignedIntValue], import.lastId);
			[data setValue:[NSNumber numberWithUnsignedInt:import.lastId] forData:@"lastid"];
		}
		
		//NSLog(@"ismainthread: %d", [NSThread isMainThread]);
		
		[self updateDisplayedDate];
		//[self performSelectorOnMainThread:@selector(updateDisplayedDate) withObject:nil waitUntilDone:YES];
	}
	
	UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:(error ? @"Error" : @"Done") message:resultString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertMessage show];
	[alertMessage autorelease];
	
	[message release];
}

#pragma mark Actions
- (void) actionsButtonClicked
{
	UIActionSheet *actionSheet = [ [UIActionSheet alloc] initWithTitle:@"Actions" 
															  delegate:self
													 cancelButtonTitle:@"Cancel"
												destructiveButtonTitle:nil
													 otherButtonTitles:@"Import contact names", nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	//[actionSheet showFromTabBar:mainView.tabBar];
	[actionSheet showInView:self];
	[actionSheet autorelease];
	//[actionSheet release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex == 0)
	{
		import.delegate = self;
		import.username = [data getData:@"username"];
		import.password = [data getData:@"password"];
		import.lastId = [[data getData:@"lastid"] unsignedIntValue];
		
		UIProgressView *progressBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
		progressBar.frame = CGRectMake(40.0, 18.0, 170.0, 9.0);
		[workingView.alertView addSubview:progressBar];
		[progressBar autorelease];
		progressBar.hidden = YES;
		import.uploadProgressDelegate = progressBar;
		
		[NSThread detachNewThreadSelector:@selector(startAddressBookImport) toTarget:import withObject:nil];
	}
}

#pragma mark Web View
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
	[self updateDisplayedDate];
}

- (void)updateDisplayedDate
{
	NSUInteger lastupload = [ [data getData:@"lastupload"] unsignedIntegerValue];
	NSLog(@"lastupload: %u", lastupload);
	
	if(lastupload > 0)
	{
		NSDate *lastuploadDateObject = [NSDate dateWithTimeIntervalSince1970:( (NSTimeInterval) lastupload)];
		
		NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
		[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
		[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
		
		NSString *displayDate = [dateFormatter stringFromDate:lastuploadDateObject];
		[webFrame stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('lastupload').innerHTML = '%@'", displayDate]];
	}
	else
	{
		[webFrame stringByEvaluatingJavaScriptFromString:@"document.getElementById('lastupload').innerHTML = 'Never'"];
	}
}

#pragma mark Navbar button
-(void)isGoingToVisible
{
	UIBarButtonItem *actionsButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionsButtonClicked)];
	[actionsButton autorelease];
	[mainView.navItem setRightBarButtonItem:actionsButton animated:NO];
}

-(void)isGoingToHidden
{
	[mainView.navItem setRightBarButtonItem:nil animated:NO];
}
@end
